import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.my.main.common.encrypt.DES3;
import com.my.main.common.encrypt.MD5;
import com.my.main.common.utils.StrUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.shiro.crypto.hash.Sha384Hash;
import org.fit.pdfdom.PDFDomTree;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.io.*;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;

public class SecretJson {
    @Autowired
    WebApplicationContext applicationContext;

    @Test
    public void asdasd() {
        List<Boolean> list = new ArrayList<>();
        list.add(true);
        list.add(true);
        list.add(false);
        list.add(true);

        System.out.println(list.stream().filter(item -> !item).count());
    }

    @Test
    // 获取secret用
    public void secretJson() throws Exception {
        // TnpKzED49UmiCRfMzGSlGEvs 为OA系统公钥
        JSONObject json = new JSONObject();
        json.put("appKey", "oa");
        json.put("oaUserId", "1262980068553424896");
        json.put("oaUserName", "刘焕鑫");
        json.put("r", Math.random());
        json.put("t", new Date().getTime());
        String jsonStr = json.toJSONString();
        String secret = DES3.encrypt(jsonStr, "TnpKzED49UmiCRfMzGSlGEvs");
        System.out.println(secret);
    }

    // 获取地址栏密钥
    @Test
    public void secretURLCode() throws Exception {
        // TnpKzED49UmiCRfMzGSlGEvs 为OA系统公钥
        JSONObject json = new JSONObject();
        json.put("token", "dbd1fc58-b8f6-4e27-b934-418ede900136");
        json.put("r", Math.random());
        json.put("t", new Date().getTime());
        String jsonStr = json.toJSONString();
        String secret = DES3.encrypt(jsonStr, "TnpKzED49UmiCRfMzGSlGEvs");
        System.out.println(secret);
    }

    @Test
    public void getQSMD5() {
        String AppToken = "AR7ZutxvHX";
        String AppSecret = "u4Zbh1e4UeQxQkiHmN0ZuCmFqydzsN";
        Long timestamp = new Date().getTime();
        //String t = timestamp.toString();
        String t = "1592834177722";
        //String t = "0";
        String uuid = UUID.randomUUID().toString();

        String str = MD5.encrypt(AppToken + AppSecret + t + uuid);
        System.out.println("时间戳:" + t);
        System.out.println("MD5:" + str);
    }

    @Test
    public void getUrlEncode () throws UnsupportedEncodingException {

        ArrayList<String> arr = new ArrayList<>();
        String input1 = "{ \"file_name\":\"测试文档1.txt\", \"file_url\":\"http://downloads.jjxsw.la/d/file/p/txt/2020/%E5%A8%87%E6%B0%94%E7%BE%8E%E4%BA%BA%E5%84%BF%E5%9C%A8%E5%85%AD%E9%9B%B6.txt\" }";
        String input2 = "{ \"file_name\":\"测试文档2.txt\", \"file_url\":\"http://downloads.jjxsw.la/d/file/p/txt/2020/%E5%A8%87%E6%B0%94%E7%BE%8E%E4%BA%BA%E5%84%BF%E5%9C%A8%E5%85%AD%E9%9B%B6.txt\" }";
        arr.add(input1);
        arr.add(input2);
        String jonsObject = JSONArray.toJSONString(arr);
        String a = "/contractCompare/compare?process_id=11111111&files_arr=" + jonsObject;
        String newURL = URLEncoder.encode(a,"UTF-8");
        // String finalUrl = "http://localhost:9527/contractCompare/compare?process_id=asdOa&files_arr=" + newURL;
        String finalUrl = "http://localhost:9527/contractCompare/compare?process_id=asdOa&files_arr=" + newURL;
        System.out.println(finalUrl);

    }

    @Test
    public void openURL () throws IOException, URISyntaxException {
        //String uri = "http://localhost:9527/contractCompare/compare?process_id=asdOa&files_arr=%5B%22%7B%20%5C%22file_name%5C%22%3A%5C%22%E6%B5%8B%E8%AF%95%E6%96%87%E6%A1%A31.txt%5C%22,%20%5C%22file_url%5C%22%3A%5C%22http%3A%2F%2Fdownloads.jjxsw.la%2Fd%2Ffile%2Fp%2Ftxt%2F2020%2F%25E5%25A8%2587%25E6%25B0%2594%25E7%25BE%258E%25E4%25BA%25BA%25E5%2584%25BF%25E5%259C%25A8%25E5%2585%25AD%25E9%259B%25B6.txt%5C%22%20%7D%22,%22%7B%20%5C%22file_name%5C%22%3A%5C%22%E6%B5%8B%E8%AF%95%E6%96%87%E6%A1%A32.txt%5C%22,%20%5C%22file_url%5C%22%3A%5C%22http%3A%2F%2Fdownloads.jjxsw.la%2Fd%2Ffile%2Fp%2Ftxt%2F2020%2F%25E5%25A8%2587%25E6%25B0%2594%25E7%25BE%258E%25E4%25BA%25BA%25E5%2584%25BF%25E5%259C%25A8%25E5%2585%25AD%25E9%259B%25B6.txt%5C%22%20%7D%22%5D";
        //Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+ "http://www.baidu.com");
        String chrome = "C:\\Users\\my23\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe";
        Map map = System.getenv();
        for (Object key : map.keySet()) {
            String value = (String) map.get(key);
            if (value.contains("chrome.exe")) {
                chrome = value;
                break;
            }
        }
        Runtime.getRuntime().exec(new String[]{chrome, "https://www.baidu.com"});
    }

    @Test
    public void browse1() throws Exception {
        String url = "https://www.baidu.com";
        String osName = System.getProperty("os.name", "");// 获取操作系统的名字

        if (osName.startsWith("Windows")) {// windows
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
        } else if (osName.startsWith("Mac OS")) {// Mac
            Class fileMgr = Class.forName("com.apple.eio.FileManager");
            Method openURL = fileMgr.getDeclaredMethod("openURL", String.class);
            openURL.invoke(null, url);
        } else {// Unix or Linux
            String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
            String browser = null;
            for (int count = 0; count < browsers.length && browser == null; count++) { // 执行代码，在brower有值后跳出，
                // 这里是如果进程创建成功了，==0是表示正常结束。
                if (Runtime.getRuntime().exec(new String[]{"which", browsers[count]}).waitFor() == 0) {
                    browser = browsers[count];
                }
            }

            if (browser == null) {
                throw new RuntimeException("未找到任何可用的浏览器");
            } else {// 这个值在上面已经成功的得到了一个进程。
                Runtime.getRuntime().exec(new String[]{browser, url});
            }
        }
    }

    @Test
    public void  getAllUrl() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

//		List<String> urlList = new ArrayList<>();
//		for (RequestMappingInfo info : map.keySet()) {
//			// 获取url的Set集合，一个方法可能对应多个url
//			Set<String> patterns = info.getPatternsCondition().getPatterns();
//
//			for (String url : patterns) {
//				urlList.add(url);
//			}
//		}

        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> map1 = new HashMap<String, String>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                map1.put("url", url);
            }

            ApiOperation anno = method.getClass().getAnnotation(ApiOperation.class);
            if (anno != null) {
                map1.put("title", anno.value()); // 类名
            }

            map1.put("className", method.getMethod().getDeclaringClass().getName()); // 类名
            map1.put("method", method.getMethod().getName()); // 方法名
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                map1.put("type", requestMethod.toString());
            }

            list.add(map1);
        }

       // JSONArray jsonArray = JSONArray.fromObject(list);

        //return jsonArray;
    }

    @Test
    public void sss() {
        String ss = new Sha384Hash("123456").toBase64();
        System.out.println(ss);
    }


    @Test
    public void testRegex() {
        String regex = ".+\\((\\d+)\\)$";
        System.out.println("样章(1)(1)(a)".matches(regex));
    }

    @Test
    public void testRegex2() {
        String aaa = "样章(1an6kn)";
        String bbb = aaa.substring(aaa.lastIndexOf("(") + 1, aaa.lastIndexOf(")"));
        System.out.println(bbb);

        String re = "[A-Za-z0-9]{6}";
        System.out.println(bbb.matches(re));


        String regex = ".+\\((\\^[a-zA-Z0-9]+)\\)$";
        System.out.println("样章(1an6kn)".matches(regex));
    }

    @Test
    public void qySecret() throws Exception {
        JSONObject json = new JSONObject();
        json.put("appKey", "qy"); // qy是“契约”的缩写，也是行一印平台的appKey
        json.put("userId", "2543042289289674882");
        json.put("userName", "彭程");
        json.put("userPhone", "15326262626");
        json.put("r", Math.random());
        json.put("t", new Date().getTime());
        String jsonStr = json.toJSONString();
        String secret = DES3.encrypt(jsonStr,
                "J0p8aoaNHWeV2DmAkqO4a6jO");
        System.out.println(secret);
    }

    @Test
    public void qyAuth() throws Exception {
        JSONObject json = new JSONObject();
        String token = "e7f0a2c3-5ea8-4b9c-b3d1-5a49041b3a9f";
        json.put("token", token);
        json.put("r", Math.random());
        json.put("t", new Date().getTime());
        String jsonStr = json.toJSONString();
        String auth = DES3.encrypt(jsonStr,
                "J0p8aoaNHWeV2DmAkqO4a6jO");
        String url = "http://192.168.1.42:9527/thirdAP?appKey=qy&auth=" + auth + "&route=%2Fdashboard";
        System.out.println(url);
    }

    @Test
    public void asd() {
        System.out.println(StrUtil.getRandomNumberString(1));
    }

    /*
    读取pdf文字
     */
    @Test
    public void readPdfTextTest() throws IOException {
        byte[] bytes = getBytes("D:\\code\\pdf\\HashMap.pdf");
        //加载PDF文档
        PDDocument document = PDDocument.load(bytes);
        readText(document);
    }

    public void readText(PDDocument document) throws IOException {
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(document);
        System.out.println(text);
    }

    /*
    pdf转换html
     */
    @Test
    public void pdfToHtmlTest()  {
        String outputPath = "C:\\Users\\my23\\Desktop\\新建文件夹\\串口服务器快速使用手册 多串口V1.html";
        byte[] bytes = getBytes("C:\\Users\\my23\\Desktop\\learn\\串口服务器快速使用手册 多串口V1.pdf");
//        try() 写在()里面会自动关闭流
        try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outputPath)),"UTF-8"));){
            //加载PDF文档
            PDDocument document = PDDocument.load(bytes);
            PDFDomTree pdfDomTree = new PDFDomTree();
            pdfDomTree.writeText(document,out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
    将文件转换为byte数组
     */
    private byte[] getBytes(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    @Test
    public void turn () throws Exception {
        try {
            String path = "C:\\Users\\my23\\Desktop\\learn\\串口服务器快速使用手册 多串口V1.pdf";
            String txtStr = readPdf(path);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 传入一个pdf文件str（文件路径）
     * @param fileStr
     * @throws Exception
     */
    public static String readPdf(String fileStr) throws Exception {
        // 是否排序
        boolean sort = true;
        File pdfFile=new File(fileStr);
        // 输入文本文件名称
        String textFile = null;
        // 编码方式
        String encoding = "UTF-8";
        // 开始提取页数
        int startPage = 1;
        // 结束提取页数
        int endPage = Integer.MAX_VALUE;
        // 文件输入流，生成文本文件
        Writer output = null;
        // 内存中存储的PDF Document
        PDDocument document = null;
        try {

            //注意参数是File。
            document = PDDocument.load(pdfFile);

            // 以原来PDF的名称来命名新产生的txt文件
            textFile=fileStr.replace(".pdf",".txt");

            // 文件输入流，写入文件倒textFile
            output = new OutputStreamWriter(new FileOutputStream(textFile),encoding);
            // PDFTextStripper来提取文本
            PDFTextStripper stripper = null;
            stripper = new PDFTextStripper();
            // 设置是否排序
            stripper.setSortByPosition(sort);
            // 设置起始页
            stripper.setStartPage(startPage);
            // 设置结束页
            stripper.setEndPage(endPage);
            // 调用PDFTextStripper的writeText提取并输出文本
            stripper.writeText(document, output);
            String text = stripper.getText(document);
            System.out.println(text);
            System.out.println(" pdf转txt成功！");
            return textFile;
        } finally {
            if (output != null) {
                // 关闭输出流
                output.close();
            }
            if (document != null) {
                // 关闭PDF Document
                document.close();
            }
        }
    }

//    Vc7I77JGA9jK8JHlsAYJVpyaYgyrA4zfUUfrMfeR+aJinjlwpPn9fijmL/i0ffDh
//    Vc7I77JGA9jK8JHlsAYJVpyaYgyrA4zfUUfrMfeR+aJinjlwpPn9fijmL/i0ffDh
    //CpievEp3tWpuK7exnZldGFzkQJDBPimEt+zG1EbUth6pmRt2pMLwSxtNJEhBRJRU

//    http://localhost:9527/thirdAP?
//    appKey=oa&auth=85A6811604A8F90632F265B6D21B3FDAB844B8F02BFE1891E4F01B65DDCC52CC310B4F9C27D2ED7776B8758B4BEB67F77833E3CDAF79015007293B7F3FE8AF61799932E593884C51A8FA99D0883D1
//7EEF4AD0C87A2E01ECBC48E8CEC42A92349&route=%2Fdashboard
//
//    http://60.16.16.90:8125/thirdAP?
//    appKey=oa&auth=A76FEC2486CFE3CD11481308182E9B679890FC9DE7E5C31359CF129435469D713EE9788993ADB69B6F59A44C27CCE3476A807AE8890B62462867F1DD40AE3C0965FA6D807573E783C9DE2DE7C8021
//    CCEBDBA84DBC2033C36AEA41E86D49F309A&route=%2Fdashboard

//    向日葵：926517590
//    验证码：5971
//    http://60.16.16.90:8125

//    http://60.16.16.90:8125/sys/thirdLogin
//    {
//        "app_id": "xm7WqsP7myTtfBkh",
//            "secret": "D5BDF1A517AFAA6B2424CB003ADBAF5785AD260179A16243E43CCD69126A27B1413208ED5F3B8338FE92A77A954AE658E1C581B35DC6869E2AC9E47D4EDFD7530D1910941848A43C9A16F9021158AE595CBDDDBD76C8BBD92C3AEAD78796213E3A134EB0BBDC18EABA9F371C6243FCB9934EBDCE2AFEEF11"
//    }

//    http://60.16.16.90:8125/thirdAP?appKey=qy&auth=QUF3ZXJxd2VycXdlcnF3ZXJxd2VycXdlcndxZXJaWg&route=%2Fdashboard
//    http://localhost:9527/thirdAP?appKey=qy&auth=QUF3ZXJxd2VycXdlcnF3ZXJxd2VycXdlcndxZXJaWg&route=%2Fdashboard
}
